<?php

namespace App\Http\Controllers\Item;

use App\Models\Item;
use App\Models\ItemCatlog;
use Illuminate\Support\Facades\DB;

class SearchController extends BaseController
{
    public function index(){

        $queryParams = [];
        $query = Item::with('shop')->onSale();

        $q = $this->request->input('q');
        if ($q) {
            $queryParams['q'] = $q;
            $query = $query->where('title', 'LIKE', "%$q%");
        }

        $catid = $this->request->input('catid');
        if ($catid) {
            $queryParams['catid'] = $catid;
            $catIds = ItemCatlog::fetchAllChildIds($catid);
            $query = $query->whereIn('catid', $catIds);
        }

        $sort = $this->request->input('sort');
        if ($sort) {
            $queryParams['sort'] = $sort;
            if ($sort == 'sale-desc'){
                $query = $query->orderByDesc('sold');
            }elseif ($sort == 'price-asc'){
                $query = $query->orderBy('price');
            } else {
                $query = $query->orderBy('itemid');
            }
        } else {
            $query = $query->orderBy('itemid');
        }
        $items = $query->paginate(20);
        $totalCount = $items->total();
        $pagination = $items->appends($queryParams)->render();

        $hotSaleList = Item::onSale()->orderByDesc('sold')->limit(5)->get();

        $this->assign(compact('q', 'catid', 'sort', 'items', 'totalCount', 'pagination', 'hotSaleList'));

        return $this->view('item.search');
    }
}
